package io.adminboot.web;

import io.adminboot.domain.form.LoginForm;
import io.adminboot.entity.User;
import io.adminboot.manager.TokenManager;
import io.adminboot.service.UserService;
import io.adminboot.system.validator.ValidatorUtils;
import io.adminboot.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 *
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {
	@Autowired
	private UserService userService;
	@Autowired
	private TokenManager tokenManager;

	/**
	 * 登录
	 */
	@PostMapping("login")
	@ApiOperation("登录")
	public R login(@RequestBody @Validated LoginForm form) {
		// 表单校验
		ValidatorUtils.validateEntity(form);

		// 用户登录
		User user = userService.login(form);

		// 生成token
		String token = tokenManager.generateToken(user);

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		return R.ok(map);
	}

}
